// @ts-ignore
import { ref } from '@vue/runtime-core'
// @ts-ignore
import { ElMessage } from 'element-plus'
// @ts-ignore
import { systemAPI } from '../api/system'
// @ts-ignore
import type { UserShortcut } from '../types/shortcut'

export const useShortcutSettings = () => {
  // 快捷键设置相关的响应式数据
  const loading = ref(false)
  const saving = ref(false)
  const shortcuts = ref<UserShortcut[]>([])
  
  const editDialogVisible = ref(false)
  
  const editingShortcut = ref<UserShortcut>({
    id: 0,
    userId: 0,
    type: '',
    moduleId: '',
    key: '',
    action: '',
    description: ''
  })
  
  const originalEditingShortcut = ref<UserShortcut>({
    id: 0,
    userId: 0,
    type: '',
    moduleId: '',
    key: '',
    action: '',
    description: ''
  })
  
  // 加载快捷键设置
  const loadShortcuts = async () => {
    loading.value = true
    try {
      const response = await systemAPI.getUserShortcuts()
      if (response.data) {
        shortcuts.value = response.data
      }
    } catch (error: any) {
      console.error('加载快捷键设置失败:', error)
      ElMessage.error('加载快捷键设置失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  
  // 编辑快捷键
  const editShortcut = (shortcut: UserShortcut) => {
    editingShortcut.value = { ...shortcut }
    originalEditingShortcut.value = { ...shortcut }
    editDialogVisible.value = true
  }
  
  // 处理按键输入
  const handleKeyInput = (event: KeyboardEvent) => {
    event.preventDefault()
    
    const keys = []
    if (event.ctrlKey || event.metaKey) keys.push('Ctrl')
    if (event.altKey) keys.push('Alt')
    if (event.shiftKey) keys.push('Shift')
    
    // 处理按键
    if (event.key.length === 1) {
      keys.push(event.key.toUpperCase())
    } else if (event.key.startsWith('F') && event.key.length > 1) {
      keys.push(event.key)
    } else {
      // 特殊键处理
      const keyMap: Record<string, string> = {
        ' ': 'Space',
        'Enter': 'Enter',
        'Escape': 'Esc',
        'Backspace': 'Backspace',
        'Tab': 'Tab'
      }
      if (keyMap[event.key]) {
        keys.push(keyMap[event.key])
      }
    }
    
    if (keys.length > 0) {
      editingShortcut.value.key = keys.join('+')
    }
  }
  
  // 保存快捷键编辑
  const saveShortcutEdit = () => {
    // 检查快捷键是否冲突
    const conflict = shortcuts.value.find(
      (s: UserShortcut) => s.key === editingShortcut.value.key && 
      s.id !== editingShortcut.value.id
    )
    
    if (conflict) {
      ElMessage.error('快捷键冲突，请选择其他组合')
      return
    }
    
    // 更新快捷键
    const index = shortcuts.value.findIndex(
      (s: UserShortcut) => s.id === editingShortcut.value.id
    )
    
    if (index !== -1) {
      shortcuts.value[index] = { ...editingShortcut.value }
    }
    
    editDialogVisible.value = false
    ElMessage.success('快捷键已更新')
  }
  
  // 保存设置
  const saveSettings = async () => {
    try {
      saving.value = true
      // 保存配置
      await systemAPI.updateUserShortcuts(shortcuts.value)
      ElMessage.success('设置已保存')
      return true
    } catch (error: any) {
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      saving.value = false
    }
  }
  
  // 重置设置
  const resetSettings = async () => {
    try {
      // 这里可以调用重置API或者使用默认值
      // 暂时使用模拟数据
      await new Promise(resolve => setTimeout(resolve, 500))
      ElMessage.success('已重置为默认设置')
      loadShortcuts()
      return true
    } catch (error) {
      ElMessage.error('重置失败')
      throw error
    }
  }
  
  return {
    // 数据
    loading,
    saving,
    shortcuts,
    editDialogVisible,
    editingShortcut,
    originalEditingShortcut,
    
    // 方法
    loadShortcuts,
    editShortcut,
    handleKeyInput,
    saveShortcutEdit,
    saveSettings,
    resetSettings
  }
}